package com.sigmazero13.bgjeeves;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;

import android.app.Service;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Binder;
import android.os.IBinder;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.util.Xml;

public class GameImageService extends Service {
	private final IBinder mBinder = new LocalBinder();

	public class LocalBinder extends Binder {
		GameImageService getService() {
			return GameImageService.this;
		}
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}
	
	
	private InputStream getThumbnailFileStream(String thumbFile) {
		InputStream is;
		File f = getFileStreamPath(thumbFile);
		if (!f.exists() || f.length()==0) {
			return null;
		}
		
		try {
			is = openFileInput(thumbFile);
		} catch (FileNotFoundException e) {
			is = null;
		}
		
		return is;
	}
	
	
	public Drawable getThumbnail(Integer gameId) {
		InputStream is;
		String thumbFile = "thumb_" + gameId.toString();
		is = getThumbnailFileStream(thumbFile);
		if (is == null) {
			GameEntryImageParser parser = new GameEntryImageParser(gameId);
			is = parser.getThumbnailInputStream();
			try {
				byte [] data = new byte [500];
				OutputStream os = openFileOutput(thumbFile, MODE_PRIVATE);
				int bytesRead = 0;
				while ( (bytesRead = is.read(data)) > 0 ) {
					os.write(data, 0, bytesRead);
				}
				os.close();
				is.close();
			} catch (FileNotFoundException e) {
			} catch (IOException e) {
			} catch (NullPointerException e) {
			}
			
			is = getThumbnailFileStream(thumbFile);
		}
		
		Drawable d;
		if (is != null) {
			d = new BitmapDrawable(is);
		} else {
			d = this.getResources().getDrawable(R.drawable.game_image_not_found);
		}
		return d;
	}
	
	
	
	private class GameEntryImageParser {
		private Integer gameId;
		
		public GameEntryImageParser(Integer gameId) {
			this.gameId = gameId;
		}
		
		private InputStream getGameInputStream() {
			Formatter f = new Formatter();
			String gameUrl = f.format(getString(R.string.bgg_thing_url), gameId).out().toString();
			try {
				return new URL(gameUrl).openConnection().getInputStream();
			} catch (Exception e) {
				return null;
			}
		}
		
		private String getThumbnailURL() {
			final List<String> thumbnailList = new ArrayList<String>();
			
			RootElement root = new RootElement("items");
			root.getChild("item").getChild("thumbnail").setEndTextElementListener(new EndTextElementListener() {
				
				@Override
				public void end(String body) {
					thumbnailList.add(body);
				}
			});
			
			try {
				Xml.parse(getGameInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
			} catch (Exception e) {
				return "";
			}
			
			if (!thumbnailList.isEmpty()) {
				return thumbnailList.get(0);
			} else {
				return "";
			}
		}
		
		public InputStream getThumbnailInputStream() {
			try {
				return new URL(getThumbnailURL()).openConnection().getInputStream();
			} catch (Exception e) {
				return null;
			}
		}
	}


}
